package com.jpxx.netty.heartBeat;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;


public class ClientHeartBeatHandler extends ChannelHandlerAdapter{  
	
	private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
	
	private ScheduledFuture<?> heartBeat;
	
	//向服务器发送认证的信息
	private InetAddress addr;
	
	private static final String SUCCESS_KEY = "auth_success_key";
	
	
	
	@Override  
	public void channelActive(ChannelHandlerContext ctx) throws  Exception {  
		System.out.println("第一步---Cllent  go······注册验证~~");
	 
			addr = InetAddress.getLocalHost();
			String ip = addr.getHostAddress();
			String key = "1234";
			//证书
			String auth = ip+","+key;
			//System.out.println("auth:"+auth);
			ctx.writeAndFlush(auth);
	}  

	@Override  
	public void channelRead(ChannelHandlerContext ctx, Object msg) {  
		System.out.println("第二步---channelRead");
		try {
			//instanceof判断是不是字符串类型
			if(msg instanceof String ){
				String ret = (String)msg;
				if(SUCCESS_KEY.equals(ret)){
					this.heartBeat = this.scheduler.scheduleWithFixedDelay(new HeartBeatTask(ctx), 0, 2,TimeUnit.SECONDS); //第一次0秒  后面2秒中一次
					System.out.println("验证成功，msg为 ："+msg);
				}else{
					System.out.println(msg);
				}
			}
		}finally{
			ReferenceCountUtil.release(msg);//不往客户端写东西，每次执行完 就释放清空一次
		}
	}
	
	//线程任务 实现了runable接口
	private class HeartBeatTask implements Runnable{
		private final ChannelHandlerContext ctx;//在线程内部用了 所以用final
		
		public HeartBeatTask(final ChannelHandlerContext ctx){
			this.ctx = ctx;
		}
		
		@Override
		public void run() {
			try {
				Sigar sigar = new Sigar();
				//cpu
				CpuPerc cpuPerc =sigar.getCpuPerc();
				HashMap<String,Object> cpuPercMap = new HashMap<String,Object>();
				cpuPercMap.put("combined", cpuPerc.getCombined());
				cpuPercMap.put("user", cpuPerc.getUser());
				cpuPercMap.put("sys", cpuPerc.getSys());
				cpuPercMap.put("wait", cpuPerc.getWait());
				cpuPercMap.put("idle", cpuPerc.getIdle());
				//memory内存
				Mem mem = sigar.getMem();
				HashMap<String,Object> memoryMap = new HashMap<String,Object>();
				memoryMap.put("total", mem.getTotal()/1024L);
				memoryMap.put("used", mem.getUsed()/1024L);
				memoryMap.put("free", mem.getFree()/1024L);
				
				RequestInfo info = new RequestInfo();
				info.setIp(addr.getHostAddress());//通过InetAddress拿客户端IP
				info.setCpuPercMap(cpuPercMap);//放入RequestInfo
				info.setMemoryMap(memoryMap);//放入RequestInfo
				ctx.writeAndFlush(info);//写回客户端
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

	
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//System.out.println("channelReadComplete+读取完毕");  
	}

	@Override  
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws  Exception{  
		cause.printStackTrace();
		if(heartBeat!=null){
			heartBeat.cancel(true);
			heartBeat=null;
		}
		ctx.fireExceptionCaught(cause);  
	}  

	
}  